package org.xiyu.yee.pjwto.mixin;

import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.monster.piglin.Piglin;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Items;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.xiyu.yee.pjwto.Constants;
import org.xiyu.yee.pjwto.trading.PiglinTradeManager;
import org.xiyu.yee.pjwto.trading.PiglinTradeMenu;

/**
 * Mixin 类用于拦截玩家与猪灵的交互
 */
@Mixin(Piglin.class)
public class PiglinInteractionMixin {
    
    @Inject(method = "mobInteract", at = @At("HEAD"), cancellable = true)
    private void onPlayerInteract(Player player, InteractionHand hand, CallbackInfoReturnable<InteractionResult> cir) {
        Piglin piglin = (Piglin)(Object)this;
        
        // 只在服务端处理
        if (player.level().isClientSide) {
            return;
        }
        
        ServerPlayer serverPlayer = (ServerPlayer) player;
        
        // 检查是否可以进行交易（空手右键）
        if (hand == InteractionHand.MAIN_HAND && 
            PiglinTradeManager.canTradeWithPiglin(piglin, serverPlayer)) {
            
            Constants.LOG.info("Opening piglin trade menu for player {}", player.getName().getString());
            
            // 打开交易界面
            PiglinTradeMenu.openTradeMenu(piglin, serverPlayer);
            cir.setReturnValue(InteractionResult.SUCCESS);
            return;
        }
        
        // 如果玩家手持金锭，让原版逻辑处理
        if (player.getItemInHand(hand).is(Items.GOLD_INGOT)) {
            // 不拦截，让原版交易逻辑继续
            return;
        }
    }
}
